import Router from "vue-router"
import Vue from "vue"
// import { Empty } from 'vant';

// Vue.use(Empty);

const layout = () => import('../page/layout.vue')
const home = () => import('../page/home.vue')
const cate = () => import('../page/cate.vue')/* 购物车 */
const cart = () => import('../page/cart.vue')
const my = () => import('../page/my.vue')/* 我的 */
const login = () => import('../page/login.vue')/* 登录 */
const register = () => import('../page/register.vue')/* 注册 */
const list = () => import('../page/list.vue')/*列表 */
const details = () => import('../page/details.vue')/* 详情 */


Vue.use(Router)
const router = new Router({
    mode: 'history',
    routes: [
        {
            path: '/',
            component: layout,
            //子路由
            children: [
                { path: 'home', component: home },
                { path: 'home/list/:id', component: list },
                { path: 'home/details/:id', component: details },
                { path: 'cate', component: cate },
                { path: 'cart', component: cart },
                { path: 'my', component: my },
            ]
        },
        {
            path: '/login',
            name: 'login',
            component: login
        },
        {
            path: '/register',
            name: 'register',
            component: register
        },
        {
            path: '*',
            redirect: '/home',
        },
    ]
})


router.beforeEach((to, from, next) => {
    if (to.path == '/cart') {
        // 既不是首页又不是登录页，就需要登录
        let isLogin = JSON.parse(localStorage.getItem('userInfo'))
        if (isLogin) {  
            // 已登录
            next()
        } else {
            // 未登录
            next('/login')
        }
    } else {
        // 去登录或者首页不拦截
        next()
    }
})

export default router